package stack;

import java.util.LinkedList;

public class BasicCalculatorii227 {
    public int calculate(String s) {
        LinkedList<Integer> stack = new LinkedList<>();
        int cur = 0;
        char pre = '+';

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if(c==' '){
                continue;
            }
            if (!Character.isDigit(c)) {
                resolve(stack,cur,pre);
                cur = 0;
                pre = c;
            } else {
                cur = cur * 10 + c - '0';
            }
        }
        resolve(stack,cur,pre);
        return stack.stream().reduce((o1, o2) -> {
            return o1 + o2;
        }).get();
    }
    private void resolve(LinkedList<Integer> stack,int cur,char pre){
        if (pre == '*') {
            stack.push(stack.pop() * cur);
        }
        if (pre == '/') {
            stack.push(stack.pop() / cur);
        }
        if (pre == '+') {
            stack.push(cur);
        }
        if (pre == '-') {
            stack.push(-cur);
        }
    }

}
